﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Bird.Data
{
    public class BirdObjectContext : DbContext, IDbContext
    {
        public BirdObjectContext(string nameOrConnectionString)
            : base(nameOrConnectionString)
        {
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            Assembly currentAssembly = Assembly.GetExecutingAssembly();
            Type configurationType = typeof(EntityTypeConfiguration<>);
            foreach (var mapType in currentAssembly.GetTypes())
            {

                if (mapType.BaseType != null && mapType.BaseType.IsGenericType &&
                    mapType.BaseType.GetGenericTypeDefinition() == configurationType)
                {
                    dynamic instance = Activator.CreateInstance(mapType);
                    modelBuilder.Configurations.Add(instance);
                }
            }
            base.OnModelCreating(modelBuilder);
        }


        public string CreateDatabaseScript()
        {

            return ((IObjectContextAdapter)this).ObjectContext.CreateDatabaseScript();
        }


        public new IDbSet<TEntity> Entities<TEntity>() where TEntity : Core.BaseEntity
        {
            return base.Set<TEntity>();
        }
    }
}
